//
//  NSAttributedString+Ex.swift
//  Pods
//
//  Created by 100Years on 2025/8/20.
//

extension NSAttributedString {
    public static func highlightSubstring(in string: String,
                                 substring: String? = nil,
                                 highlightColor: UIColor = .red,
                                 defaultColor: UIColor = .black,
                                 highlightFont: UIFont? = nil,
                                 defaultFont: UIFont = .systemFont(ofSize: 16)) -> NSAttributedString {
        let attributedString = NSMutableAttributedString(string: string)
        let fullRange = NSRange(location: 0, length: string.utf16.count)
        
        // 设置默认属性
        attributedString.addAttributes([
            .foregroundColor: defaultColor,
            .font: defaultFont
        ], range: fullRange)
        
        guard let substring = substring else { return attributedString }
        
        // 查找所有匹配的子字符串
        let substringLength = substring.utf16.count
        var searchRange = NSRange(location: 0, length: string.utf16.count)
        
        while searchRange.location < string.utf16.count {
            let foundRange = (string as NSString).range(of: substring, options: [], range: searchRange)
            if foundRange.location != NSNotFound {
                // 设置高亮属性
                var attributes: [NSAttributedString.Key: Any] = [.foregroundColor: highlightColor]
                if let highlightFont = highlightFont {
                    attributes[.font] = highlightFont
                }
                attributedString.addAttributes(attributes, range: foundRange)
                
                // 移动搜索范围
                searchRange.location = foundRange.location + foundRange.length
                searchRange.length = string.utf16.count - searchRange.location
            } else {
                break
            }
        }
        
        return attributedString
    }
}
